<?php

namespace Hilaoyu\LaravelExtend\Services\Auth\Controllers;

use Hilaoyu\LaravelExtend\ControllerBase;
use Hilaoyu\LaravelExtend\Services\Auth\AuthService;
use Hilaoyu\LaravelExtend\Services\Captcha\CaptchaService;
use Hilaoyu\LaravelExtend\Supports\Uuid;
use Hilaoyu\Utils\UtilRegex;
use Hilaoyu\Utils\UtilSupport;
use Illuminate\Http\Request;

class RegisterController extends ControllerBase
{


    protected function showRegisterForm(Request $request)
    {
        comResponse()->with(AuthService::GuardKey(), 'guard');
        return $this->renderingResponse();
    }

    public function register(Request $request)
    {
        $data = $request->input();

        $guard_key = AuthService::GuardKey();
        try {
            $mobile = data_get($data, 'mobile', '');
            $account = (string)data_get($data, 'account', $mobile);
            $password = (string)data_get($data, 'password', '');

            if(!$account || !$password){
                throw new \Exception('账号密码不能为空');
            }

            /*$user = UtilSupport::tryQuiet(function () use ($account){
                $credentials = [
                    'account' =>$account
                ];
                return AuthService::LoadUser($credentials,AuthService::GuardKey());
            });
            if($user){
                throw new \Exception('账号已存在');
            }*/

            if(true !== ($check = AuthService::CheckPasswordHandle($password,$user))){
                comResponse()->withErrors($check,'password');
                throw new \Exception((string)$check);
            }

            $captchaService = new CaptchaService();


            if (AuthService::GetGuardProviderConfig(AuthService::GuardKey(),'register_need_mobile') && !$mobile) {
                throw new \Exception('手机号不能为空');
            }
            if($mobile){
                if (!UtilRegex::isMobile($mobile)) {
                    throw new \Exception('手机号错误');
                }
                /*$user = UtilSupport::tryQuiet(function () use ($mobile){
                    $credentials = [
                        'mobile' =>$mobile
                    ];
                    return AuthService::LoadUser($credentials,AuthService::GuardKey());
                });
                if($user){
                    throw new \Exception('手机号已存在');
                }*/
                if(AuthService::GetGuardProviderConfig(AuthService::GuardKey(),'register_check_mobile')){
                    $code_mobile_id = $request->input('code_mobile_id', '');
                    $code_mobile_val = $request->input('code_mobile_val', '');
                    if(!$captchaService->verify($code_mobile_id,$code_mobile_val,$mobile)){
                        throw new \Exception('手机验证码错误');
                    }
                }

            }

            $email = data_get($data, 'email', '');
            if (AuthService::GetGuardProviderConfig(AuthService::GuardKey(),'register_need_email')&& !$email) {
                throw new \Exception('邮箱不能为空');
            }
            if ($email) {

                if (!UtilRegex::isEmail($email)) {
                    throw new \Exception('邮箱格式错误');
                }

                /*$user = UtilSupport::tryQuiet(function () use ($email){
                    $credentials = [
                        'email' =>$email
                    ];
                    return AuthService::LoadUser($credentials,AuthService::GuardKey());
                });

                if($user){
                    throw new \Exception('邮箱已存在');
                }*/

                if (AuthService::GetGuardProviderConfig(AuthService::GuardKey(),'register_check_email')) {
                    $code_email_id = $request->input('code_email_id', '');
                    $code_email_val = $request->input('code_email_val', '');
                    if (!$captchaService->verify($code_email_id, $code_email_val, $email)) {
                        throw new \Exception('邮箱证码错误');
                    }
                }
            }

            if (!data_get($data, 'name')) {
                $data['name'] = data_get($data, 'account');
            }

            if(true !== ($msg=AuthService::RegisterCheckBefore($data))){
                //comResponse()->withErrors(AuthService::GetStaticError());
                throw new \Exception($msg);
            }

            $chexk_exists = true;
            $user_id = '';
            //如果作为客户端使用，先在用户中心注册
            if($client = AuthService::ProviderUseAsClient()){
                $data = $client->register($data);
                if(!$data){
                    comResponse()->withErrors($client->getError());
                    throw new \Exception($client->getResult('message'));
                }

                if ($user = AuthService::LoadUser(['account' => $account], $guard_key)) {
                    $user_id = data_get($user, 'id', '');
                    $data = collect($data)->only([
                        'id',
                        'password',
                        'mobile',
                        'email',
                        'sex',
                        'name',
                        'date_of_birth',
                    ])->toArray();
                }
                $chexk_exists = false;
            }else{
                $data['password'] = AuthService::PasswordEn($password,$guard_key);
            }

            if($user = AuthService::SaveUser($data,$user_id,$guard_key,$chexk_exists)){
                comResponse()->success('注册成功');
            }else{
//                comResponse()->withErrors(AuthService::GetStaticError());
                throw new \Exception((string)AuthService::GetStaticError(false));
            }
        }catch (\Exception $exception){
            $message = $exception->getMessage();
            if(!$message){
                $message = '注册失败';
            }
            comResponse()->failed($message);
        }


        return $this->renderingResponse();
    }
}
